from api.database import db
from passlib.hash import pbkdf2_sha256 as sha256


class User(db.Model):
  __tablename__ = 'users'
  id = db.Column(db.Integer, primary_key=True)
  username = db.Column(db.String(120), unique=True, nullable=False)
  password = db.Column(db.String(1000), nullable=False)

  def create(self):
    try:
      db.session.add(self)
      db.session.commit()
      return self
    except Exception as e:
      db.session.rollback()  # 回滚事务
      raise e  # 重新抛出异常

  @classmethod
  def find_by_username(cls, username):
    return cls.query.filter_by(username=username).first()

  @classmethod
  def find_by_id(cls, user_id):
    """
    根据用户 ID 查找用户。
    :param user_id: 用户的 ID
    :return: 如果找到用户，返回用户对象；否则返回 None
    """
    return cls.query.filter_by(id=user_id).first()

  @staticmethod
  def generate_hash(password):
    return sha256.hash(password)

  @staticmethod
  def verify_hash(password, hash):
    return sha256.verify(password, hash)
